const Router = require("koa-router");

const { Sequelize } = require("sequelize");
const { Order } = require("@models/order");
const { Auth } = require("@middlewares/auth");
const { Goods } = require("@models/goods");
const { User } = require("@models/user");
const { Op } = require("sequelize");
const router = new Router({
  prefix: "/admin/order",
});

// 获取订单列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const {
    page = 1,
    pageSize = 10,
    order_status = "",
    order_number = "",
    phone = "",
  } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where =
    order_status != ""
      ? {
          order_status,
          order_number: {
            [Op.like]: `%${order_number}%`,
          },
        }
      : {
          order_number: {
            [Op.like]: `%${order_number}%`,
          },
        };
  const { count: total, rows } = await Order.findAndCountAll({
    where,
    offset,
    limit: pageSize,
    order: [["created_at", "DESC"]],
    include: [
      {
        model: Goods,
        required: false,
      },
      {
        model: User,
        where: {
          phone: {
            [Op.like]: `%${phone}%`,
          },
        },
        attributes: ["phone", "user_name", "avatar"],
      },
    ],
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});
// 获取订单详情
router.post("/detail", new Auth().m, async (ctx, next) => {
  const { order_id } = ctx.request.body;

  const order = await Order.findOne({ where: { order_id } });
  if (!order) {
    throw new global.errs.AuthFailed("订单不存在");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: order,
  };
});

// 更新订单状态
router.post("/update", new Auth().m, async (ctx, next) => {
  const { order_id, ...res } = ctx.request.body;
  const order = await Order.update({ ...res }, { where: { order_id } });
  if (order[0] == 0) {
    throw new global.errs.AuthFailed("更新失败");
  }
  ctx.body = {
    code: 200,
    msg: "更新成功",
  };
});

// 删除订单
router.post("/delete", new Auth().m, async (ctx, next) => {
  const { order_id } = ctx.request.body;
  const order = await Order.destroy({ where: { order_id } });
  if (order === 0) {
    throw new global.errs.AuthFailed("删除失败");
  }
  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

module.exports = router;
